package com.yami.shop.api.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.api.security.AuthenticationToken;
import com.yami.shop.bean.dto.UserPass;
import com.yami.shop.bean.enums.SmsType;
import com.yami.shop.bean.model.AppVersion;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.UserForget;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.dao.AppVersionMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.security.handler.LoginAuthSuccessHandler;
import com.yami.shop.security.model.AppConnect;
import com.yami.shop.security.service.YamiUserDetailsService;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.SmsLogService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;

/**
 * 用户信息
 *
 * @author SJL
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户注册相关接口")
@AllArgsConstructor
public class UserRegisterController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final SmsLogService smsLogService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AppVersionMapper appVersionMapper;

    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "用户注册或绑定手机号接口")
    public ResponseEntity<Boolean> register(@Valid @RequestBody UserRegisterParam userRegisterParam) {
//        userRegisterParam.setPassword(userRegisterParam.getPassword());

        boolean b = smsLogService.checkValidCode(userRegisterParam.getUserMobile(), userRegisterParam.getCode(), SmsType.VALID);
        if(b){
            do {
                userRegisterParam.setInvitatioCode(userService.createShareCode());
            }while (userMapper.invitatioCodeRepeat(userService.createShareCode()) > 0);

            return ResponseEntity.ok(userService.insertUser(userRegisterParam));
        }else{
            throw new YamiShopBindException("验证码错误或已过期");
        }
    }

    @PutMapping("/updatePwd")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public ResponseEntity<Void> updatePwd(@Valid @RequestBody UserPass userRegisterParam) {
        User user = userService.getUserByUserMobile(userRegisterParam.getUserMobile());
        if (user == null) {
            // 无法获取用户信息
            throw new YamiShopBindException("无法获取用户信息");
        }
        if (StrUtil.isBlank(userRegisterParam.getPassword())) {
            // 新密码不能为空
            throw new YamiShopBindException("新密码不能为空");
        }
        if (userRegisterParam.getPassword().equals(user.getLoginPassword())) {
            // 新密码不能与原密码相同3
            throw new YamiShopBindException("新密码不能与原密码相同");
        }
        /*if (StrUtil.equals(passwordEncoder.encode(userRegisterParam.getPassword()), user.getLoginPassword())) {
            // 新密码不能与原密码相同
            throw new YamiShopBindException("yami.user.no.exist");
        }*/
        if (!userRegisterParam.getLoginPassword().equals(user.getLoginPassword())) {
            // 老密码要与现密码相同
            throw new YamiShopBindException("旧密码不正确");
        }
        user.setModifyTime(new Date());
        user.setLoginPassword(userRegisterParam.getPassword());
        //user.setLoginPassword(passwordEncoder.encode(userRegisterParam.getPassword()));
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }



    @GetMapping("/phoneIsReg")
    @ApiOperation(value = "忘记密码接口",notes = "忘记密码接口")
    public ResponseEntity<Boolean> phoneIsReg(UserForget userForget){
        boolean b = smsLogService.checkValidCode(userForget.getUserMobile(), userForget.getCode(), SmsType.VALID);
        if(b){
            return ResponseEntity.ok(userService.insertForget(userForget));
        }else{
            throw new YamiShopBindException("验证码错误或已过期");
        }
    }

    @GetMapping("/judgeInv")
    @ApiOperation(value = "判断邀请码性别",notes = "判断邀请码性别(1表示男，2表示女，3表示邀请码不存在，4表示邀请码重复)")
    public ResponseEntity<Integer> judgeInv(String code){
        return ResponseEntity.ok(userService.judgeInv(code));
    }

    @GetMapping("/judgeModel")
    @ApiOperation(value = "判断手机号有没有注册账号",notes = "判断手机号有没有注册账号")
    public ResponseEntity<Integer> judgeModel(String Model){
       User user = userMapper.selectOne(new QueryWrapper<User>()
        .eq("user_mobile",Model));
       if (user != null){
           return ResponseEntity.ok(1);
       }else {
           return ResponseEntity.ok(0);
       }


    }

    @GetMapping("/appVersion")
    @ApiOperation(value = "版本更新接口",notes = "返回最新版本信息以及地址，前端进行对比")
    public ResponseEntity<AppVersion> appVersion(){
        return ResponseEntity.ok(appVersionMapper.getVersion());
    }


}
